import axios from 'axios'
import { Message } from 'element-ui'
import store from '../store/index'
import config from './config'

const service = axios.create({
  baseURL: config.baseUrl,
  withCredentials: true
})

service.interceptors.request.use(
  config => {
    if (config.method.toLowerCase() === 'get') {
      config.params = {
        random: Math.random(),
        ...config.params
      }
    }
    return config
  },
  error => {
    console.error(error)
    Promise.reject(error)
  }
)

service.interceptors.response.use(
  response => {
    if (response.data.retCode === 2) {
      Message({
        message: response.data.msg,
        type: 'error',
        duration: 5 * 1000
      })
      return Promise.reject(response)
    } else if (response.data.retCode === 1) {
      store.dispatch('LogOut').then(() => {
        location.reload()
      })
      return Promise.reject(response)
    } else if (response.data === null || typeof response.data.retCode === 'undefined') {
      Message({
        message: '未知错误',
        type: 'error',
        duration: 5 * 1000
      })
      return Promise.reject(response)
    }
    return response
  },
  /**
   * 下面的注释为通过在response里，自定义code来标示请求状态
   * 当code返回如下情况则说明权限有问题，登出并返回到登录页
   * 如想通过 xmlhttprequest 来状态码标识 逻辑可写在下面error中
   * 以下代码均为样例，请结合自生需求加以修改，若不需要，则可删除
   */
  error => {
    if (error.response.status === 403) {
      store.dispatch('LogOut').then(() => {
        location.reload()
      })
    } else {
      console.error('err' + error)
      Message({
        message: error.message,
        type: 'error',
        duration: 5 * 1000
      })
    }
    return Promise.reject(error)
  }
)

export default service
